/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.plugin.websocket;

import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mcgrobot.common.sysenum.McgWsOperationEnum;
import com.mcgrobot.config.WebSocketConfig;
import com.mcgrobot.entity.auth.PermissionCollection;
import com.mcgrobot.entity.auth.UserCacheBean;
import com.mcgrobot.entity.ws.McgWsInfo;
import com.mcgrobot.util.Tools;

@ServerEndpoint(value = "/message",configurator = WebSocketConfig.class)
@Component
public class McgWebSocket {

	private static Logger logger = LoggerFactory.getLogger(McgWebSocket.class);
	
    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private String httpSessionId;
    
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        onlineCount.incrementAndGet(); // 在线数加1
        logger.info("有新连接加入：{},httpSessionId：{}，当前在线人数为：{}", session.getId(), config.getUserProperties().get("httpSessionId"), onlineCount.get());
        httpSessionId = config.getUserProperties().get("httpSessionId").toString();
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        logger.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	UserCacheBean ucb = PermissionCollection.getInstance().getUserCache(httpSessionId);
    	if(ucb != null) {
	    	logger.debug("接收数据：{}, sessionId:{}", message, session.getId());
	    	McgWsInfo mcgWsInfo = null;
	    	try {
	    		mcgWsInfo = JSON.parseObject(message, McgWsInfo.class);
	    	} catch (Exception e) {
	    		logger.error("mcgWebSocket接收到非法指令:{}, 异常信息:", message, e);
	    		return ;
			}
	    	if(McgWsOperationEnum.INIT.getValue().equals(mcgWsInfo.getOperation())) {
	        	if(ucb != null && ucb.getUser() != null) {
	        		ucb.getUser().getWebSocketMap().put(Tools.genMcgWsConnUniqueId(mcgWsInfo.getMcgWebScoketCode() , httpSessionId), session);
	        	}
	    	}
    	}
    }

    @OnError
    public void onError(Session session, Throwable error) {
    	logger.error("非法关闭一个websocket通道成功, webSocketSessionId:{}, 异常信息:", session.getId() , error);
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
    	/*
        try {
        	logger.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
        	logger.error("服务端发送消息给客户端失败：{}", e);
        }
        */
    }
}
